package service

import (
	"gowork/memberGoKit/server/dao"
	"gowork/memberGoKit/model"
	"fmt"

	"context"
	"net/url"
	"io"
	"os"
	"github.com/go-kit/kit/endpoint"
	"github.com/go-kit/kit/sd"
	"github.com/go-kit/kit/sd/lb"
	"github.com/go-kit/kit/log"
	httpTransport "github.com/go-kit/kit/transport/http"
	
	stuTransport "gowork/studentGoKit/client/transport"
	stuEndpoint "gowork/studentGoKit/client/endpoint"
	stuUtil "gowork/studentGoKit/client/util"

	"github.com/afex/hystrix-go/hystrix"
	"time"
)

type MemberSriImp struct{
	Dip *dao.MemberDaoImp
}

func (msi *MemberSriImp)InesrtSri(mb []*model.Member)map[string]string{
	var d = dao.MemberDaoImp{}
	msi.Dip = &d
	return msi.Dip.InesrtDao(mb)
}

func (msi *MemberSriImp)QuerySri() []*model.Member{
	var d = dao.MemberDaoImp{}
	msi.Dip = &d

	
	//调用studentGoKit服务
	sfactory := func(serviceUrl string)(endpoint.Endpoint, io.Closer, error){
		start, _ := url.Parse("http://" + serviceUrl)
		return httpTransport.NewClient("GET", start, stuTransport.StudentQueryRequest, stuTransport.StudentQueryResponse).Endpoint(), nil, nil
	}

	sendpointer := sd.NewEndpointer(stuUtil.Instancer, sfactory, log.NewLogfmtLogger(os.Stdout))

	//负载均衡
	mysLb := lb.NewRoundRobin(sendpointer)
	//myLb := lb.NewRandom(endpointer, time.Now().UnixNano())
	
	studentQueryFunc, uErr := mysLb.Endpoint()
	if uErr != nil{
		fmt.Println(uErr)
		return nil
	}

	configHystrix := hystrix.CommandConfig{
		Timeout: 1000,
		MaxConcurrentRequests: 5,
		RequestVolumeThreshold: 3,
		ErrorPercentThreshold: 20,
		SleepWindow: int(time.Second*100),
	}
	hystrix.ConfigureCommand("studentQuery", configHystrix)
	var sres interface{}
	var err error
	err = hystrix.Do("studentQuery", func() error{
		ctx := context.Background()
		sres, err = studentQueryFunc(ctx, stuEndpoint.StudentNilRequest{})
		return err
	}, func(e error) error{
		sres = map[string]string{
			"code" : "500",
			"message" : "服务降级",
		}
		return nil
	})
	if err != nil{
		fmt.Println(err)
	}

	// sctx := context.Background()
	// sres, serr := studentQueryFunc(sctx, stuEndpoint.StudentNilRequest{})
	// if serr != nil{
	// 	fmt.Println(serr)
	// 	return nil
	// }
	
	fmt.Println("studentList:", sres)


	return msi.Dip.QueryDao()
}